import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/home/HomeView.vue'
import Layout from '@/views/Layout.vue'
import User from '@/views/user/User.vue'
import Kind from '@/views/kind/Kind.vue'
import Book from '@/views/book/Book.vue'
import Infor from '@/views/infor/Infor.vue'
import Login from '@/views/login/Login.vue'
import Cookies from 'js-cookie'
import Register from '@/views/register/Register.vue'
import Update from '@/views/update/Update.vue'
import Borrow from '@/views/access/Borrow.vue'


Vue.use(VueRouter)

const routes = [
  // 登录
  {
    path:'/login',
    name:'Login',
    component:Login
  },
  // 主页
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect:'/page',
    children:[ //子路由
      {
        path:'/page',
        name:'Home',
        component:HomeView
      },
      {
        path: 'user',
        name: 'User',
        component: User
      }
      ,
      {
        path: 'kind',
        name: 'Kind',
        component: Kind
      },
      {
        path:'book',
        name:'Book',
        component:Book
      },
      {
        path:'infor',
        name:'Infor',
        component:Infor
      },
      {
        path:'update',
        name:'Update',
        component:Update
      },
      {
        path:'borrow',
        name:'Borrow',
        component:Borrow
      }
    ]
  },
  // 注册
  {
    path:'/register',
    name:'Register',
    component:Register
  },
  // 404
  {
    path:'*',
    component:()=>import('@/views/404.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/register'||to.path === '/login'){
    next()
  }else{
    const admin = Cookies.get("admin")
    if (!admin && to.path !== '/login'){
      return next("/login")
    }else{
      next()
    }
  } 
})

export default router
